import request from '../js/axios';
import {defineStore} from "pinia";
import router from "@/router/index.js";
import Toast, {useToast} from "vue-toastification";
import {getAllScore, updateScore} from "@/hook/scoreHook.js";
import {getAllAdmin, getAllStudent, getAllTeacher} from "@/hook/userHook.js";

export let useUserStore = defineStore('user', {
    state: () => ({
        users:[],
        search_username:'',
        search_type:'',
        currentUser: {
            username:''
        },
        user:{
            id: 0, 
            username: '',
            password: '',
            realName: '',
            role: '',
            email: '',
            phone: '',
            gender: '',
            createdAt: '',
            isAdmin: 0,
        },
        isAuth:0,
        token:null,
    }),
    getters: {
        // doubleCount: (state) => state.count * 2,
    },
    actions: {
        login:async function(username,password) {
            return request.post('/auth/login',{
                "username":username,
                "password":password
            }).then((res)=>{
                if(res.data.code==0){
                    this.token= res.data.data
                    this.isAuth = 1
                    return true
                }
                throw "账户或密码错误"
            }).catch((error)=>{
                console.error(error ,"登录失败")
                this.token= null
                this.isAuth = 0
                return false
            })
        },
        getUserInfo:async function(){
            return request.get(`/user/getUserInfo?username=${localStorage.getItem('username')}`)
                .then((res)=>{
                if(res.data.code==0){
                    this.user = res.data.data
                    console.log(res.data)
                    return true
                }
                throw "获取用户信息失败"
            }).catch((error)=>{
                return false
            })
        },
        updateUser:async function(){
            console.log(this.currentUser)
            return request.post('/user/updateUser',this.currentUser).then(async (res) => {
                if (res.data.code == 0) {
                    useToast().success("用户修改成功")
                    return true
                }
                throw ""
            }).catch((error)=>{
                if(useUserStore().search_type==='学号'){
                    useToast().error('修改失败，请学号是否唯一')
                }else if(useUserStore().search_type==='教师号'){
                    useToast().error('修改失败，请教师号是否唯一')
                }else if(useUserStore().search_type==='管理员'){
                    useToast().error('修改失败，请检查管理员是否唯一')
                }
                return false
            })
        },
        addUser : (user) => {
            return request.post('/user/addUser',user)
                .then((res) => {
                    if(res.data.code === 0) {
                        useToast().success("添加加成功")
                        return res.data.data;
                    }
                    throw ""
                }).catch((err) => {
                    if(useUserStore().search_type==='学号'){
                        useToast().error('添加学生失败')
                    }else if(useUserStore().search_type==='教师号'){
                        useToast().error('添加教师失败')
                    }else if(useUserStore().search_type==='管理员'){
                        useToast().error('添加管理员失败')
                    }
                    return false
                })
        },
        updateStudents:async function(pageNo,PageSize) {
            this.users = await getAllStudent(pageNo,PageSize,this.search_username);
        },
        updateTeachers:async function(pageNo,PageSize) {
            this.users = await getAllTeacher(pageNo,PageSize,this.search_username);
        },
        updateAdmins:async function(pageNo,PageSize) {
            this.users = await getAllAdmin(pageNo,PageSize,this.search_username);
        },
        clearUsers:function () {
            this.users=[];
            this.search_username = '';
            // this.search_type = '';
        }
    },
})
export let useScoreStore = defineStore('score', {
    state: () => ({
        scores:[],
        currentScore:{
            id:0,
            score:0,
        },
        msg:'',
        type:'',
    }),
    getters: {
        // doubleCount: (state) => state.count * 2,
    },
    actions: {
        update:async function(score) {
            await updateScore(score)
        },
        updateScores:async function(pageNo,PageSize) {
            this.scores = await getAllScore(pageNo,PageSize,this.msg,this.type);
        },
    },
})